<?php

namespace app\api\controller;

use app\common\model\AdminModel;
use app\common\model\ArticleModel;
use think\Controller;
use think\Request;

class Article extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        //
        $key = $request->param('key');
        $page = $request->param('page');
        $limit = $request->param('limit');
        $db = new ArticleModel();
        if(isset($key) && !empty($key)){
            $db = $db->where('title','like','%'.$key.'%');
        }
        $list = $db->page($page)->limit($limit)->select();
        $total = $db->count('id');
        return json(['code'=>1,'data'=>$list,'total'=>$total]);

    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $data = $request->param();
        $db = new ArticleModel();
        if (isset($data['id']) && !empty($data['id'])){
            $res = $db->save($data,['id'=>$data['id']]);

        }else{
            $res = $db->save($data);

        }

        if($res){
            return json(['code'=>1,'msg'=>'更新成功']);
        }else{
            return json(['code'=>0,'msg'=>'更新失败']);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(Request $request)
    {
        //
        $id = $request->param('id');
        $db = new ArticleModel();
        $res = $db->where('id',$id)->delete();
        if($res){
            return json(['code'=>1,'msg'=>'删除成功']);

        }else{
            return json(['code'=>0,'msg'=>'删除失败'.$id]);

        }

    }
}
